#import "TDGetCarPlaceSelC.h"
#import "TBROncarPlaceCellCell.h"
@interface TDGetCarPlaceSelC ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *tf_searchStr;

@property (nonatomic,strong)BMKPoiSearch *poiSearch;
@property (nonatomic,strong)BMKCitySearchOption *citySearchOption;
@property (nonatomic,strong)BMKNearbySearchOption *nearbySearchOption;
@property (nonatomic,copy)NSString *searchStr;//搜索内容当没有搜索内容时候显示历史信息还是当前位置信息-----------

//地图定位服务
@property (nonatomic, strong) BMKLocationService *locationService;

/***
 <存储地图定位自己和目标位置坐标>
 ***/
@property (nonatomic)CLLocationCoordinate2D beginingCoordinate;

@property (nonatomic)CLLocationCoordinate2D destinationCoordinate;

/***
 <存储定位地图的位置名称>
 ***/
@property (nonatomic , strong)NSString *myNameStr;
@property (nonatomic , strong)NSString *toNameStr;

@property (nonatomic,strong)NSMutableArray *suggestSearchArray;//搜索建议的数组
@property (nonatomic,strong)NSMutableArray *seachArray;//搜索的数组
//@property (nonatomic,strong)BMKSuggestionSearchOption *option;//搜索建议


@end
@implementation TDGetCarPlaceSelC
- (void)viewDidLoad {
    [super viewDidLoad];
    _searchStr = @"";
    [self setSuggestionSearch];//设置建议-----
    [self startLocation];//定位--------
    [self setupTableView];
    _suggestSearchArray = [NSMutableArray array];
    _seachArray = [NSMutableArray array];
    [_tf_searchStr addTarget:self action:@selector(searchStrChange:) forControlEvents:UIControlEventEditingChanged];
    if (_isOnCarPlace) {
        _tf_searchStr.placeholder = @"您在哪上车";
    }
}


- (IBAction)navBtnClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchStrChange:(UITextField *)tf {
    self.searchStr = tf.text;
    if ([HelpObject isBlankString:self.searchStr]) {
        [self.tableView reloadData];
        return;
    }
    //
    [self setBMKSearchWith:nil];
}

- (void)setupTableView {
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"TBROnCarPlaceCellCell" bundle:nil] forCellReuseIdentifier:@"TBROnCarPlaceCellCellId"];
    self.tableView.rowHeight = 70;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}



#pragma mark - 实现数据源方法
#pragma mark - 返回组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - 返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [HelpObject isBlankString:_searchStr] ?  self.suggestSearchArray.count : self.seachArray.count;
}

#pragma mark - 返回每行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //自定义cell
    TBROnCarPlaceCellCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TBROnCarPlaceCellCellId" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    TBROnCarPlaceModel *model;
    if ([HelpObject isBlankString:self.searchStr]) {
        model = self.suggestSearchArray[indexPath.row];
    }else {
        model = self.seachArray[indexPath.row];
    }
    
    cell.model = model;
    //    TBRTextMapModel *model = self.suggestSearchArray[indexPath.row];
    //    cell.textLabel.text = model.titleName;
    //设置数据
    //返回
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TBROnCarPlaceModel *model;
    if ([HelpObject isBlankString:self.searchStr]) {
        model = self.suggestSearchArray[indexPath.row];
    }else {
        model = self.seachArray[indexPath.row];
    }
    
    if ([HelpObject isBlankString:model.detailStr]) {
        return 44;
    }
    return 70;
}





-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    TBROnCarPlaceModel *model;
    if ([HelpObject isBlankString:self.searchStr]) {
        model = self.suggestSearchArray[indexPath.row];
    }else {
        model = self.seachArray[indexPath.row];
    }
    
    //
    
    if (self.onCarPlaceBlock) {
        [self.navigationController popViewControllerAnimated:YES];
        self.onCarPlaceBlock(model);
    }
}

- (void)setSuggestionSearch {
    //此处不使用搜索建议  而是使用poi检索来实现-------------------------
    //    _suggestionSearch = [[BMKSuggestionSearch alloc]init];
    //    _suggestionSearch.delegate = self;
    //    self.option = [[BMKSuggestionSearchOption alloc]init];
    self.poiSearch = [[BMKPoiSearch alloc] init];
    self.poiSearch.delegate = self;
    self.citySearchOption = [[BMKCitySearchOption alloc] init];
    self.nearbySearchOption = [[BMKNearbySearchOption alloc] init];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _poiSearch.delegate = self;
    _locationService.delegate = self;
    [_locationService startUserLocationService];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _poiSearch.delegate = nil;
    _locationService.delegate = nil;
    [self.view endEditing:YES];
}

- (void)startLocation {
    [self progressHUDShowWithText:@"定位中..."];
    _locationService = [[BMKLocationService alloc] init];
    _locationService.delegate = self;
    [_locationService startUserLocationService];
}


/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    CLLocation *location = userLocation.location;
    BMKCoordinateSpan span;
    span.latitudeDelta = 0.5;
    span.longitudeDelta = 0.5;
    BMKCoordinateRegion region;
    region.center = location.coordinate;
    region.span = span;
    //    [self setBMKSearchWith:userLocation];
    //停止定位
    [_locationService stopUserLocationService];
    CLLocationCoordinate2D coor;
    coor.latitude = userLocation.location.coordinate.latitude;
    coor.longitude = userLocation.location.coordinate.longitude;
    
    //反地理编码----不需要的  后续删除-------
    //    注意：必须初始化地理编码类
    BMKGeoCodeSearch *_geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
    _geoCodeSearch.delegate = self;
    BMKReverseGeoCodeOption *reverseOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseOption.reverseGeoPoint = coor;
    [_geoCodeSearch reverseGeoCode:reverseOption];
    //--------------------------------------------------
    [self progressHUDShowWithCompleteText:@"定位成功" isSucceed:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tf_searchStr becomeFirstResponder];
    });
}

- (void)didFailToLocateUserWithError:(NSError *)error {
    [self progressHUDShowWithCompleteText:@"定位失败" isSucceed:NO];
}


#pragma mark - 代理方法返回反地理编码结果
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    self.suggestSearchArray = [NSMutableArray array];
    if (result) {
        //获取城市
        for (int i = 0; i < result.poiList.count; i++) {
            BMKPoiInfo* info = [result.poiList objectAtIndex:i];
            TBROnCarPlaceModel *carPlacaModel = [[TBROnCarPlaceModel alloc] init];
            carPlacaModel.titleStr = info.name;
            carPlacaModel.detailStr = info.address;
            carPlacaModel.coordPt = info.pt;
            [self.suggestSearchArray addObject:carPlacaModel];
        }
        [self.tableView reloadData];
    }
}


// MARK: - 实现poi搜索----------
- (void)setBMKSearchWith:(BMKUserLocation *)userLocation{
    
    if (userLocation) {
        //说明是第一次进入页面  此时要实现当前位置的搜索--------------历史搜索放在那里...
        self.nearbySearchOption.location = userLocation.location.coordinate;
        self.nearbySearchOption.radius = 2000;//搜索半径设置-----
        self.nearbySearchOption.keyword = @"地铁";
        //是否进行排序的设置默认排序是综合排序 可以设置从近到远来排序----------
        BOOL flag = [_poiSearch poiSearchNearBy:_nearbySearchOption];
        if (flag) {
            NSLog(@"周边检索发送成功");
        }else{
            NSLog(@"周边检索发送失败");
        }
        return;
    }
    
    //    BMKNearbySearchOption  BMKCitySearchOption
    //    // 设置地图级别
    //    [self.mapView setZoomLevel:17];
    //    self.mapView.isSelectedAnnotationViewFront = YES; //设定是否总让选中的annotaion置于最前面
    _citySearchOption.pageIndex = 0;
    _citySearchOption.pageCapacity = 20;//默认是10条//
    _citySearchOption.city = @"上海";
    _citySearchOption.keyword = self.searchStr;
    BOOL flag = [_poiSearch poiSearchInCity:_citySearchOption];
    if (flag) {
        NSLog(@"检索发送成功");
    }else{
        NSLog(@"检索发送失败");
    }
    //    citySearchOption.
    //    /***
    //     <这个值本来是传过来的不是固定的，我这里写的固定是方便大家看>
    //     ***/
    ////    option.keyword = @"成都市金牛区万达广场";
    //    option.location = userLocation.location.coordinate;
    //
    ////    self.beginingCoordinate = option.location;
    //    NSLog(@"option.loction == %f  %f", self.beginingCoordinate.latitude, self.beginingCoordinate.longitude);
    //    option.radius = 10000;
    //
    //    /***
    //     <因为我需要一个定位所以我就拿一个位置的信息>
    //     ***/
    //    option.pageCapacity = 1;
    //
}


#pragma mark implement BMKSearchDelegate
/***
 <检索数据回调，数据都在BMKPoiResult里边，拿出来想怎么用都行>
 ***/
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error{
    self.seachArray = [NSMutableArray array];
    if (error == BMK_SEARCH_NO_ERROR) {
        //        result.currPoiNum = 1;
        for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* info = [result.poiInfoList objectAtIndex:i];
            TBROnCarPlaceModel *carPlacaModel = [[TBROnCarPlaceModel alloc] init];
            carPlacaModel.titleStr = info.name;
            carPlacaModel.detailStr = info.address;
            carPlacaModel.coordPt = info.pt;
            [self.seachArray addObject:carPlacaModel];
            //            mapMark* item = [[mapMark alloc]init];
            //            item.coordinate = poi.pt;
            //            self.destinationCoordinate = item.coordinate;
            //            NSLog(@"%f  %f", self.destinationCoordinate.longitude ,  self.destinationCoordinate.latitude);
            //
            //            item.title = poi.name;
            //            NSLog(@"self.title%@",item.title);
            //            item.type = 1;
            //            [self.dataArr addObject:poi];
            //            [annotations addObject:item];
        }
        
        
        [self.tableView reloadData];
    } else if (error == BMK_SEARCH_PERMISSION_UNFINISHED){
        NSLog(@"用户没有授权");
    } else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD) {
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
        // result.cityList;
        NSLog(@"起始点有歧义");
    }
    else{
        NSLog(@"检索失败：%d",error);
    }
}

@end
